package filesearcher;
/**
 *
 * @author Misiacik
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.activation.FileDataSource;
import javax.swing.filechooser.FileSystemView;
import jxl.Cell;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class WriteExcel {

    private WritableCellFormat timesBoldUnderline;
    private static WritableCellFormat times;
    private String inputFile;
    private static int position;

    public void setOutputFile(String inputFile) {
        this.inputFile = inputFile;
    }

    public void write(List<String> directories, SearcherFrame.WritingToFile writingActivity) throws IOException, WriteException, IllegalArgumentException {
        File tempFile = new File("c:/temp/temp.xls");
        boolean tempExists = tempFile.exists();
        if(tempExists)  // checks if temporary file exists
            delete("c:/temp/temp.xls");
        boolean exists = (new File(inputFile)).exists();
        if (exists) {   // input file already exist - data will be added
            Workbook workbook = null;
            try{
                workbook = Workbook.getWorkbook(new File(inputFile));   // throws BiffException
            } catch (BiffException ex){
                throw new IOException("Can't be open Original Excel File");
            }
            WritableWorkbook copy = Workbook.createWorkbook(new File("c:/temp/temp.xls"), workbook);
            WritableSheet excelSheet = copy.getSheet(0);
            createLabel(excelSheet); //creates headers

            position = excelSheet.getRows();
            for(String directory : directories){
                createContent(excelSheet, directory, writingActivity); // creates content
            }
            //WriteExcel.sort(excelSheet);
            copy.write(); // writes into workBook
            copy.close(); // close the workBook
            try{
                delete(inputFile);  //throws IllegalArgumentException
            } catch(IllegalArgumentException ex){
                tempExists = (new File("c:/temp/temp.xls")).exists();
                if(tempExists)
                    delete("c:/temp/temp.xls");
                throw new IllegalArgumentException("Output Excel File is Open");
            }
            rename("c:/temp/temp.xls", inputFile);
        } 
        else {  // input file doesn't exist - file will be created
            File file = new File(inputFile); // creates new file
            WorkbookSettings wbSettings = new WorkbookSettings(); // creates new workBook settings
            wbSettings.setLocale(new Locale("en", "EN"));
            WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings); // creates workBook with file name and settings
            workbook.createSheet("Report", 0); // create new sheet at possition 0
            WritableSheet excelSheet = workbook.getSheet(0); // retutns sheet 0
            createLabel(excelSheet); //creates headers

            position = 1;
            for(String directory : directories){
                createContent(excelSheet, directory, writingActivity); // creates content
            }

            workbook.write(); // writes into workBook
            workbook.close(); // close the workBook
        }
    }

    private void createLabel(WritableSheet sheet) throws WriteException {
        // Lets create a times font
        WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
        // Define the cell format
        times = new WritableCellFormat(times10pt);

        // Create create a bold font with unterlines
        WritableFont times15ptBoldUnderline = new WritableFont(WritableFont.TIMES, 15, WritableFont.BOLD, false, UnderlineStyle.SINGLE);
        timesBoldUnderline = new WritableCellFormat(times15ptBoldUnderline);

        CellView cv = new CellView();
        cv.setFormat(times);
        cv.setFormat(timesBoldUnderline);
        cv.setAutosize(true);

        // Write headers
        addCaption(sheet, 0, 0, "File Name");
        addCaption(sheet, 1, 0, "Disk Name");
        addCaption(sheet, 2, 0, "Location");
    }

    private void createContent(WritableSheet sheet, String directory, SearcherFrame.WritingToFile writingActivity) throws WriteException, RowsExceededException, FileNotFoundException {
        File driveLetter= new File(directory.substring(0, 3));  //find drive letter
        String driveName = FileSystemView.getFileSystemView().getSystemDisplayName (driveLetter);   //find drive name
        File startingDirectory= new File(directory);    //open directory
        List<File> files = FileListing.getFileListing(startingDirectory);   //put files into the list
        int progress = 0;
        for(File file : files){ //write file names into Excel file
            if(writingActivity.isCancelled()){ // if user manualy cancel writingActivity
                break;
            }
            writingActivity.setWriringProgress(progress, file);
            
            if (progress >= 100)
                progress = 0;
            else
                progress++;

            if(!file.isDirectory() && !file.isHidden()){
                String fileName = file.getName();
                String path = file.getPath();
                FileDataSource ds = new FileDataSource(path);
                String contentType = ds.getContentType();
                System.out.println("The MIME type of the file " + fileName + " is: " + contentType);

                if(contentType.contains("video")){
                    // First column
                    addLabel(sheet, 0, position, fileName);
                    // Second column
                    addLabel(sheet, 1, position, driveName.substring(0, driveName.length()-5));  //extract only name of the drive
                    // Third column
                    addLabel(sheet, 2, position, path.substring(3));  //cut letter part from the path
                    position++;
                } //end IF
            } //end IF
        } //end FOR
    } //end function

    private void addCaption(WritableSheet sheet, int column, int row, String s)
                throws RowsExceededException, WriteException {
        Label label;
        label = new Label(column, row, s, timesBoldUnderline);
        sheet.addCell(label);
    }

    private static void addLabel(WritableSheet sheet, int column, int row, String s)
            throws WriteException, RowsExceededException {
        Label label;
        label = new Label(column, row, s, times);
        sheet.addCell(label);
    }

    private static void editLabel(WritableSheet sheet, int column, int row, String content)
            throws WriteException, RowsExceededException {
//        Label label;
//        label = new Label(column, row, s, times);
//        sheet.addCell(label);
        WritableCell cell = sheet.getWritableCell(column, row);
        Label label = (Label) cell;
        label.setString(content);
    }

    private static void sort(WritableSheet excelSheet) throws WriteException {
        List<String> rows = new ArrayList<String>();
        position = excelSheet.getRows();
        for(int i=1; i<position; i++){
            Cell cell = excelSheet.getCell(0, i);
            rows.add(cell.getContents());
        }
        Collections.sort(rows);
        //System.out.println("Size of List is: " + rows.size());
        int i=1;
        for(String row:rows){
            editLabel(excelSheet, 0, i, row);
            i++;
        }
    }

    public static void delete(String fileName) {
        File f = new File(fileName);

        if (!f.exists())
          throw new IllegalArgumentException(
              "Delete: no such file or directory: " + fileName);

        if (!f.canWrite())
          throw new IllegalArgumentException("Delete: write protected: "
              + fileName);

        if (f.isDirectory()) {
          String[] files = f.list();
          if (files.length > 0)
            throw new IllegalArgumentException(
                "Delete: directory not empty: " + fileName);
        }

        boolean success = f.delete();

        if (!success)
          throw new IllegalArgumentException("Delete: deletion failed");
  }

    public static void rename(String oldName, String newName) {
        File f1 = new File(oldName);
        File f2 = new File(newName);

        if (!f1.exists())
          throw new IllegalArgumentException(
              "Delete: no such file or directory: " + oldName);

        if (!f1.canWrite())
          throw new IllegalArgumentException("Delete: write protected: "
              + oldName);

        boolean success = f1.renameTo(f2);

        if (!success)
          throw new IllegalArgumentException("Delete: deletion failed");
  }

}
